<script setup>
import { nextTick, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import goodApi from "@/api/goodApi";
import goodAttrApi from "@/api/goodAttrApi";
import constants from "@/utils/constants";
import Upload from "@/components/Upload.vue";

const router = useRouter();

const attrs = ref([
  { label: '4英寸', value: '272', code: "008", size: "12cm x 12cm", laidSize: "5", shareSize: "1～2人享用" },
  { label: '5英寸', value: '279', code: "009", size: "13cm x 13cm", laidSize: "5", shareSize: "1～3人享用" },
  { label: '6英寸', value: '224', code: "010", size: "15cm x 15cm", laidSize: "5", shareSize: "3～4人享用" },
  { label: '8英寸', value: '226', code: "020", size: "20cm x 20cm", laidSize: "10", shareSize: "5～6人享用" },
  { label: '10英寸', value: '228', code: "030", size: "25cm x 25cm", laidSize: "15", shareSize: "9～10人享用" },
  { label: '个', value: '280', code: "299", size: "个", laidSize: "5", shareSize: "1～2人享用" },
  { label: '盒', value: '244', code: "220", size: "盒", laidSize: "5", shareSize: "1～2人享用" },
]);

const submitForm = ref();
const searchForm = ref();
const searchModel = reactive({
  goodsName: "",
});
const visible = ref(false);
let uploadVisible = ref(false);
const loading = ref(false);

let submitData = ref({ goodsDesc: "", goodsThumb: "" });

let pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
  showPageSize: true,
  pageSizeOptions: [15, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search(current, pagination.pageSize);
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search(pagination.current, size);
  },
});

const columns = [
  {
    title: "商品编码",
    dataIndex: "goodsId",
    width: 100,
  },
  {
    title: "商品图片",
    slotName: "goodsThumb",
    width: 120,
  },
  {
    title: "商品名称",
    dataIndex: "goodsName"
  },
  {
    title: "是否上架",
    slotName: "isOnSale",
    width: 100,
  },
  {
    title: "排序",
    dataIndex: "sortOrder",
    width: 60,
  },
  {
    title: "操作",
    slotName: "action",
    align: 'center',
    fixed: "right",
    width: 200,
  },
];

const attrColumns = [
  {
    title: "尺寸编码",
    slotName: "attrId",
    width: 100,
  },
  {
    title: "属性值",
    slotName: "attrValue",
    width: 100,
  },
  {
    title: "尺寸规格",
    slotName: "attrDesc",
    width: 100,
  },
  {
    title: "尺寸描述",
    slotName: "attrSize",
    width: 100,
  },
  {
    title: "餐具",
    slotName: "laidSize",
    width: 100,
  },
  {
    title: "人数",
    slotName: "shareSize",
    width: 100,
  },
  {
    title: "价格",
    slotName: "attrPrice",
    width: 100,
  },
  {
    title: "操作",
    slotName: "action",
    align: 'center',
    fixed: "right",
    width: 100,
  },
];

const data = ref([]);

const showAddDialog = () => {
  visible.value = true;
  submitForm.value.resetFields();
  submitData.value.goodAttrList = [];
};

const editRecord = (record) => {
  visible.value = true;
  nextTick(() => {
    submitForm.value.resetFields();
    submitData.value = Object.assign({}, record);
  });
};

const deleteRecord = (record) => {
  goodApi.delete({ goodsId: record.goodsId }).then(res => {
    search();
  });
}

const switchSale = (record) => {
  goodApi
    .switchSale({
      goodsId: record.goodsId,
      isOnSale: !record.isOnSale
    })
    .then((res) => {
      Message.success("操作成功");
      search();
    });
};

const addGoodAttr = () => {
  if (!submitData.value.goodAttrList) {
    submitData.value.goodAttrList = [];
  }
  submitData.value.goodAttrList.push({
    goodsAttrId: "",
    goodsId: submitData.value.goodsId,
    shareSize: "",
    laidSize: "",
    attrDesc: "",
    attrPrice: "0.00",
    attrValue: "",
    attrId: ""
  })
}

const deleteGoodAttr = (index, attrModel) => {
  if (attrModel.goodsAttrId) {
    goodAttrApi.delete({ goodsAttrId: attrModel.goodsAttrId }).then(res => {
      submitData.value.goodAttrList.splice(index, 1);
    });
  } else {
    submitData.value.goodAttrList.splice(index, 1);
  }
}

const deleteGallery = (index) => {
  submitData.value.goodGalleries.splice(index, 1);
}

const addGoodGallery = () => {
  let sortArray = submitData.value.goodGalleries.map(obj => obj.orderSort)
  const maxSort = Math.max(...sortArray);
  submitData.value.goodGalleries.push({
    orderSort: maxSort + 1,
    imgUrl: "",
    imgId: "",
    imgType: 3
  })
}

const handleSubmitSuccess = (values, e) => {
  goodApi.save(values).then((res) => {
    visible.value = false;
    Message.success("保存成功");
    search();
  });
};

const search = () => {
  var params = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  goodApi.queryPage(params).then((res) => {
    data.value = res.records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const refresh = () => {
  search();
};

const getNationName = (value) => {
  let nationItem = constants.nationList.find((res) => {
    return res.value == value;
  });
  return !nationItem ? "" : nationItem.label;
};

const reset = () => {
  searchForm.value.resetFields();
};

search();
</script>

<template>
  <a-card>
    <a-row>
      <a-col :flex="1">
        <a-form ref="searchForm" layout="vertical" :model="searchModel" :label-col-props="{ span: 8 }"
          :wrapper-col-props="{ span: 16 }" label-align="left">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item field="goodsName" label="商品名称">
                <a-input v-model="searchModel.goodsName" placeholder="请输入商品名称" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="catId" label="商品分类">
                <a-select v-model="searchModel.catId" allow-clear placeholder="请选择" :options="constants.catList">
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="isOnSale" label="是否上架">
                <a-select v-model="searchModel.isOnSale" allow-clear placeholder="请选择"
                  :options="constants.onSaleStatues">
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-col>
      <a-divider style="height: 84px" direction="vertical" />
      <a-col :flex="'86px'" style="text-align: right">
        <a-space direction="vertical" :size="18">
          <a-button type="primary" @click="refresh">
            <template #icon>
              <icon-search />
            </template>
            查询
          </a-button>
          <a-button @click="reset">
            <template #icon>
              <icon-refresh />
            </template>
            重置
          </a-button>
        </a-space>
      </a-col>
    </a-row>
  </a-card>
  <a-card style="margin-top: 20px">
    <div class="toolbar">
      <a-space>
        <a-button type="primary" @click="showAddDialog">
          <template #icon>
            <icon-plus />
          </template>
          新增商品
        </a-button>
      </a-space>
    </div>
    <a-table :columns="columns" row-key="goodsId" :loading="loading" :data="data" @page-change="pagination.pageChange"
      @page-size-change="pagination.pageSizeChange" :pagination="pagination" :bordered="false">
      <template #goodsThumb="{ record }">
        <a-image :src="constants.imgDomain + record.goodsThumb + '?imageslim/zlevel/7'" width="50"></a-image>
      </template>
      <template #isOnSale="{ record }">
        <a-tag :color="record.isOnSale ? '#00AAFF' : ''">{{ record.isOnSale ? '已上架' : '未上架' }}</a-tag>
      </template>
      <template #action="{ record }">
        <a-space>
          <a-button size="mini" type="primary" @click="editRecord(record)">编辑</a-button>
          <a-popconfirm v-if="!record.isOnSale" content="确认要上架该商品吗？" @ok="switchSale(record)">
            <a-button size="mini" type="outline">上架</a-button>
          </a-popconfirm>
          <a-popconfirm v-if="record.isOnSale" content="确认要下架该商品吗？" @ok="switchSale(record)">
            <a-button size="mini" type="outline">下架</a-button>
          </a-popconfirm>
          <a-popconfirm content="确认要删除该数据吗？" @ok="deleteRecord(record)">
            <a-button size="mini" type="primary" status="danger">删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>
  </a-card>
  <a-modal v-model:visible="visible" width="70%" title="新增/编辑商品" :footer="null">
    <a-form ref="submitForm" size="large" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
      :model="submitData" @submit-success="handleSubmitSuccess">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="goodsThumb" label="商品主图">
            <Upload tip="上传主图" :height="120" :width="120" v-model="submitData.goodsThumb"></Upload>
          </a-form-item>
          <a-form-item field="goodsName" label="商品名称" :rules="[{ required: true, message: '请输入商品名称' }]">
            <a-input v-model="submitData.goodsName" placeholder="请输入商品名称" />
          </a-form-item>
          <a-form-item field="sortOrder" label="商品排序" :rules="[{ required: true, message: '请输入商品排序' }]">
            <a-input-number v-model="submitData.sortOrder" mode="button" placeholder="请输入商品排序" />
          </a-form-item>
          <a-form-item field="goodsNumber" label="商品库存" :rules="[{ required: true, message: '请输入商品库存' }]">
            <a-input-number v-model="submitData.goodsNumber" mode="button" placeholder="请输入商品库存" />
          </a-form-item>
          <a-form-item field="keywords" label="商品标签">
            <a-input v-model="submitData.keywords" placeholder="请输入商品标签 多种逗号分隔即可" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="goodsDesc" label="商品详情图">
            <Upload tip="上传详情图" :height="300" :width="200" v-model="submitData.goodsDesc"></Upload>
          </a-form-item>
        </a-col>
      </a-row>
      <a-card title="属性规格">
        <template #extra>
          <a-button @click="addGoodAttr" type="primary" size="small">
            <template #icon>
              <icon-plus />
            </template>
          </a-button>
        </template>
        <a-table :columns="attrColumns" :data="submitData.goodAttrList" style="margin-top: 20px">
          <template #attrId="{ record, rowIndex }">
            <a-select v-model="record.attrId" placeholder="请选择尺寸编码" @change="(v) => {
              let arItem = attrs.find(item => item.value == v);
              record.attrDesc = arItem.label
              record.attrValue = arItem.code
              record.attrSize = arItem.size
              record.laidSize = arItem.laidSize
              record.shareSize = arItem.shareSize
            }">
              <a-option v-for="attrItem in attrs" :label="attrItem.label" :value="attrItem.value"></a-option>
            </a-select>
          </template>
          <template #attrValue="{ record, rowIndex }">
            <a-input v-model="record.attrValue" readonly placeholder="请选择编码" />
          </template>
          <template #attrDesc="{ record, rowIndex }">
            <a-input v-model="record.attrDesc" readonly placeholder="请选择编码" />
          </template>
          <template #attrSize="{ record, rowIndex }">
            <a-input v-model="record.attrSize" readonly placeholder="请选择编码" />
          </template>
          <template #laidSize="{ record, rowIndex }">
            <a-input v-model="record.laidSize" readonly placeholder="请选择编码" />
          </template>
          <template #shareSize="{ record, rowIndex }">
            <a-input v-model="record.shareSize" readonly placeholder="请选择编码" />
          </template>
          <template #attrPrice="{ record, rowIndex }">
            <a-input v-model="record.attrPrice" placeholder="请输入商品价格">
              <template #prepend>
                ¥
              </template>
            </a-input>
          </template>
          <template #action="{ record, rowIndex }">
            <a-popconfirm content="确认要删除该数据吗？" @ok="deleteGoodAttr(rowIndex, record)">
              <a-button>
                <template #icon>
                  <icon-delete />
                </template>
              </a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </a-card>
      <a-card title="轮播图" style="margin-top: 16px;">
        <template #extra>
          <a-button @click="addGoodGallery" type="primary" size="small">
            <template #icon>
              <icon-plus />
            </template>
          </a-button>
        </template>
        <a-row :gutter="16">
          <a-col :span="4" v-for="(gallery, index) in submitData.goodGalleries" :key="gallery.imgId"
            style="margin-top: 10px;">
            <div class="flex flex-column flex-center">
              <div style="text-align: center;">
                <a-button @click="deleteGallery(index)" size="mini">
                  <template #icon>
                    <icon-delete />
                  </template>
                </a-button>
              </div>
              <div class="flex flex-center">
                <Upload tip="上传轮播图" :height="100" :width="100" v-model="gallery.imgUrl"></Upload>
              </div>
              <div class="flex flex-center" style="width: 100px;">
                <a-input-number size="mini" v-model="gallery.orderSort" mode="button"></a-input-number>
              </div>
            </div>
          </a-col>
        </a-row>
      </a-card>
      <div class="option-btn">
        <a-space>
          <a-button html-type="submit" type="primary">保存</a-button>
          <a-button @click="() => {
            visible = false;
          }
            ">取消</a-button>
        </a-space>
      </div>
    </a-form>
  </a-modal>
</template>

<style scoped></style>
